package com.example.musicreader;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    private ContentResolver resolver;
    private Button button;
    private ListView listView;
    private ImageView imageView;
    private ArrayList<Music> musicList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
    }

    private void initView() {
        button = findViewById(R.id.btn);
        listView = findViewById(R.id.listView);
        imageView = findViewById(R.id.iv_bofang);
    }

    private void initEvent() {

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readMusic();
            }
        });
    }


    private void readMusic() {
        resolver = getContentResolver();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                , new String[]{MediaStore.Audio.Media._ID
                        , MediaStore.Audio.Media.TITLE
                        , MediaStore.Audio.Media.ARTIST}
                , null, null, null);

        musicList = new ArrayList();

        while (cursor.moveToNext()) {
            Music music = new Music();
            music.setId(cursor.getString(0));
            music.setName(cursor.getString(1));
            music.setMusicArtist(cursor.getString(2));

            musicList.add(music);

        }
        Toast.makeText(this, "" + "读取完成", Toast.LENGTH_SHORT).show();
        listView.setAdapter(new MyAdapter(MainActivity.this, musicList));
    }

}